package com.liu.susu.controller;

import com.liu.susu.pojo.Dog;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;

@Controller
@RequestMapping("/dog/entityManager1")
public class EntityManagerController {

    @PersistenceContext
    private EntityManager entityManager;

    @ResponseBody
    @RequestMapping("/list1")
    public List<Dog> getDogList(){
        String sql = "select * from dog";
        List<Dog> dogList = entityManager.createNativeQuery(sql)
                .getResultList();//结果只有属性值，没有属性名
        return dogList;
    }
    @ResponseBody
    @RequestMapping("/list2")
    public List<Dog> getDogList2(){
        String sql = "select * from dog";
        List<Dog> dogList = entityManager.createNativeQuery(sql,Dog.class)
                .getResultList();//结果===>有属性名
        return dogList;
    }
    /**
     * sql注入
     *    通过参数查询
     * @param dogNum
     * @return
     */
    @ResponseBody
    @RequestMapping("/dog1")
    public Dog getDogByNum(@RequestParam Integer dogNum){
        String sql = "select * from dog d where d.dog_num=?1";
        Query query = entityManager.createNativeQuery(sql,Dog.class);
        query.setParameter(1,dogNum);
        Dog dog = (Dog) query.getSingleResult();
        return dog;
    }
    @ResponseBody
    @RequestMapping("/save")
    @Transactional()//事务注解 记得加
    public String testPersist(){
        Dog dog = new Dog();
        dog.setDogNum(1006);
        dog.setDogName("测试");
        dog.setDogAge(0);
        entityManager.persist(dog);//直接insert
        return "ok";
    }
    @ResponseBody
    @RequestMapping("/merge")
    @Transactional()//事务注解 记得加
    public String testMerge(){
        Dog dog = new Dog();
        dog.setDogNum(1006);
        dog.setDogName("测试2");
        dog.setDogAge(0);
        entityManager.merge(dog);//内部原理：先根据主键查询再update
        return "ok";
    }

}
